package org.operator.conn.conf;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ConfigDbConfig {

	private static Map<String, String> config;

	private static Map<String, String> systemConfig;

	private static Map<String, String> dbloadSql;

	/**
	 * 公共配置
	 */
	private static Map<String, Map<String, String>> commonConf = new HashMap<String, Map<String, String>>();
	
	private String fileName;
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	private static ConfigDbConfig obj;
	
	private ConfigDbConfig(String fileName) {
		
		this.fileName = fileName + ".properties";
	}
	
	/**
	 * 
	 * @param fileName
	 * @return
	 */
	public static ConfigDbConfig getInstance( String fileName) {
		if (obj == null) {    
            synchronized (ConfigDbConfig.class) {    
               if (obj == null) {    
            	   obj = new ConfigDbConfig(fileName);   
               } else {
            	   obj.setFileName(fileName + ".properties");
               }   
            }    
        } else {
        	obj.setFileName(fileName + ".properties");
        }
        return obj; 
	}
	
	/**
	 * 获取配置信息
	 * @return
	 */
	public Map<String, String> getConfig() {
		
		Map<String, String> confHas = commonConf.get(this.fileName);
		
		if (confHas != null) {
			return confHas;
		}
		
		Map<String, String> conf = this.getSource();
		
		if(conf == null) {
			return null;
		}
		
		commonConf.put(this.fileName, conf);
		
		return conf;
		
	}
	
	/**
	 * 获取数据库配置（后期扩展）
	 * 
	 * @param configName
	 *            config 文件 在resource 下
	 * @return
	 * @throws Exception
	 */
	public  Map<String, String> getDbConf() {

		if (config != null) {
			return config;
		}

		config = this.getSource();

		return config;
	}

	private  Map<String, String> getSource() {

		String path = ConfigDbConfig.class.getResource("../../../../").getPath() + this.fileName;

		try {

			BufferedInputStream fileStream = new BufferedInputStream(new FileInputStream(path));

			Properties pro = new Properties();

			pro.load(fileStream);

			Enumeration<?> en = pro.propertyNames(); // 得到配置文件的名字
			String strKey, strValue;

			Map<String, String> conf = new HashMap<String, String>();

			while (en.hasMoreElements()) {
				strKey = (String) en.nextElement();
				strValue = pro.getProperty(strKey);
				conf.put(strKey, strValue);
			}
			return conf;
		} catch (Exception e) {
			// TODO: handle exception

			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 获取系统配置（后期扩展）
	 * 
	 * @param configName
	 *            config 文件 在resource 下
	 * @return
	 * @throws Exception
	 */
	public  Map<String, String> getSystemConf() {

		if (systemConfig != null) {
			return systemConfig;
		}

		systemConfig = getSource();

		return systemConfig;
	}

	/**
	 * 获取sql 语句资源
	 * 
	 * @return
	 */
	public  Map<String, String> getLoadSql() {

		if (dbloadSql != null) {
			return dbloadSql;
		}

		String path = ConfigDbConfig.class.getResource("../../../../").getPath() + this.getSystemConf().get("db_load");

		BufferedInputStream fileStream;

		Properties pro;

		File[] file = loadManyFile(path);

		Map<String, String> conf = new HashMap<String, String>();

		Enumeration<?> en;

		String strKey, strValue;

		try {
			for (int i = 0; i < file.length; i++) {

				fileStream = new BufferedInputStream(new FileInputStream(file[i]));

				pro = new Properties();

				pro.load(fileStream);

				en = pro.propertyNames(); // 得到配置文件的名字

				while (en.hasMoreElements()) {
					strKey = (String) en.nextElement();
					strValue = pro.getProperty(strKey);
					conf.put(strKey, strValue);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		dbloadSql = conf;

		return conf;
	}

	/**
	 * 读取多级目录
	 * 
	 * @param path
	 * @return
	 */
	private static File[] loadManyFile(String path) {
		List<String> filePaths = new ArrayList<String>();
		LinkedList<File> list = new LinkedList<File>();
		File dir = new File(path);
		File[] file = dir.listFiles();

		for (int i = 0; i < file.length; i++) {
			if (file[i].isDirectory()) {
				// 把第一层的目录，全部放入链表
				list.add(file[i]);
			}
			filePaths.add(file[i].getAbsolutePath());
		}

		// 循环遍历链表
		while (!list.isEmpty()) {
			// 把链表的第一个记录删除
			File tmp = list.removeFirst();
			// 如果删除的目录是一个路径的话
			if (tmp.isDirectory()) {
				// 列出这个目录下的文件到数组中
				file = tmp.listFiles();

				if (file == null) {// 空目录
					continue;
				}
				// 遍历文件数组
				for (int i = 0; i < file.length; ++i) {
					if (file[i].isDirectory()) {
						// 如果遍历到的是目录，则将继续被加入链表
						list.add(file[i]);
					}
					filePaths.add(file[i].getAbsolutePath());
				}
			}
		}
		return file;
	}

}
